(function() {
	Application = {};
	var startTime;
	var $navMenus;

	/* 初始化导航菜单 */
	Application.initNavMenu = function(nav, sideNav) {
		$navMenus = $(nav).find('a');
		var $childNavMenus = $(sideNav).find('ul.sidebar-menu'); 
		/* 给横向菜单注册onclick方法 */
		$navMenus.each(function(i) {
			this._index=i;
			var myChildMenu = Efast.getDom('_Child' + this.id);
			if(myChildMenu){
				myChildMenu._index=this._index;
				this._childMenu = myChildMenu; // 给菜单添加childMenu属性
			}
			this.onHash = function() {
				var self = this;
				$childNavMenus.hide();
				var url = self.getAttribute('url');
				var myChildMenu = Efast.getDom('_Child' + self.id);
				$navMenus.removeClass('active');
				$(self).addClass('active');
				var iframes=$('#_contentsWrap iframe:not(#_mainContent_'+self._index+')');
				iframes.each(function(i){
					try {
						this.style.width = Efast.getDom('_contentsWrap').clientWidth + 'px';
						this.style.height = Efast.getDom('_contentsWrap').clientHeight + 'px';
					} catch (e) {
						//在ie下iframe不可见时，设置宽高会出错？？？（待证实）
					}
					this.style.position = 'absolute';
				});
				var targetIframe=Efast.getDom('_mainContent_'+self._index);
				if(!targetIframe){
					targetIframe=Dom.html2Node('<iframe id="_mainContent_'+self._index+'" name="_mainContent_'+self._index+'" class="animated fadeInRight" frameborder="0" width="100%" height="100%" src="about:blank" scrolling="auto" style="position:absolute;left:-22in;top:-11in;" allowtransparency="true"></iframe>');
					Efast.getDom('_contentsWrap').appendChild(targetIframe)
				}
				
				if (!url) {
					$('#sidebar').show();
					Efast.getDom('_contentsWrap').style.marginLeft = null;
					self._childMenu = myChildMenu; // 给菜单添加childMenu属性
					myChildMenu.onHash();
				} else {
					$('#sidebar').hide();
					Efast.getDom('_contentsWrap').style.marginLeft = '0';
					$G('splitter1')&& $('#splitter1').hide();
					$('#toggleLeftColumn').removeClass('toggleBtn-left');
					$('#toggleLeftColumn').addClass('toggleBtn-right');
				}
				targetIframe.style.position='static';
				targetIframe.style.width = "100%";
				targetIframe.style.height = "100%";	
			};
			this.onclick = function() {
				var self = this;
				var url = self.getAttribute('url');
				var menuid=self.getAttribute('menuid');
				var myChildMenu = Efast.getDom('_Child' + self.id);
				if (!url && myChildMenu) {
					self._childMenu = myChildMenu; // 给菜单添加childMenu属性
					myChildMenu.onShow();
				} else {
					if (!/^#/.test(url)) {
						window.location.hash = menuid;
					}
					Efast.preventEvent();
				}
				//if(this.)$('#leftColumnWrap').show();
				//$G('splitter1')&& $('#splitter1').show();
				$('#toggleLeftColumn').removeClass('toggleBtn-right');
				$('#toggleLeftColumn').addClass('toggleBtn-left');
			};
		}); /* 给左侧菜单注册onclick方法 */
		$childNavMenus.each(function(i) {
			var childNavMenu=this;
			var $links = $(childNavMenu).find('a');
			childNavMenu.onHash = function() {
				$(childNavMenu).show();
			};
			childNavMenu.onShow = function() {
				$(childNavMenu).show();
				if (childNavMenu._activeMenu) {
					childNavMenu._activeMenu.onclick();
				} else {
					if ($links[0]) {
						$links[0].onclick();
					} else {
						window.location.hash = $navMenus[childNavMenu._index].getAttribute('menuid');
					}
				}
			}
			$links.each(function(j) {
				this.setAttribute('target','_mainContent_' + childNavMenu._index)
				this._index=j;
				this.setActiveMenu = function() {
					$links.each(function() {
						$(this.parentNode).removeClass('active');
					})
					$(this.parentNode).addClass('active');
					childNavMenu._activeMenu = this;
				};
				this.onclick = function(e) {
					e = e||window.event;
					var self = this;
					window.location.hash = childNavMenu.id.substr("_Child_Menu_".length) + '/' + (this.getAttribute('menuid'));
					Efast.preventEvent(e);

				}
			})
		})
	};
	
	//在hash值改变时
	Application._handleHashChange= function(h){
		if(!!!h){
			return;
		}
		if(!/^\w+/.test(h)){
			return;
		}
		var index = h.split('/');
		var navMenuId=index[0];
		var subNavMenuId = index[1];
		var query
		if(index.length==3){
			 query=index[2]
		}else if(index.length==2){
			if(index[1].indexOf('=')>-1){
				query=index[1];
				subNavMenuId=null;
			}
		}
		query=query?'?'+query:'';
		var navMenu = Efast.getDom('_Menu_' + navMenuId);
		if (!navMenu) {
			navMenu=$navMenus[0];
		}
		if(!navMenu) {
			return;
		}
		navMenu.onHash();
		var url = navMenu.getAttribute('url');
		var targetIframe=Efast.getDom('_mainContent_'+navMenu._index);
		if(url){
			$('#sidebar').hide();
			$G('splitter1')&& $('#splitter1').hide();
			$('#toggleLeftColumn').removeClass('toggleBtn-left');
			$('#toggleLeftColumn').addClass('toggleBtn-right');
			if (!/^#/.test(url)) {
				if(!targetIframe.src.endsWith(url+query)){
					//Server.loadWidthProcess(targetIframe.contentWindow.document, url+query, false);
					//targetIframe.src = 'javascript:document.write("'+url+'")';
					targetIframe.src = url+query;
					var menuid = navMenu.getAttribute('menuid');
					Server.sendRequest("Application.changeMenuClickCount",{AppID:CurrentApp,MenuID:menuid,Hash:h},null);
				}
			}
		} else {
			$('#sidebar').show();
		}

		if(subNavMenuId){
			var childNavMenu = Efast.getDom('_Child_Menu_' + navMenuId);
			if (!childNavMenu) {
				return;
			}
			$(childNavMenu).show();
			var $links = $(childNavMenu).find('a');
			var link;
			$links.each(function(){
				if(this.getAttribute('menuid') && this.getAttribute('menuid')==subNavMenuId){
					link=this;
					return false;
				}
			});
			if (link) {
				link.setActiveMenu();
				var url = link.getAttribute("href"),
				target = link.getAttribute("target");
				var targetIframe=Efast.getDom(target);
				if (!/^#/.test(url)) {
					if(!targetIframe.src.endsWith(url+query)){
						//targetIframe.src = 'javascript:document.write("'+url+'")';
						targetIframe.src = url+query;
//						Server.loadWidthProcess(targetIframe.contentWindow.document, url+query, false);
						Server.sendRequest("Application.changeMenuClickCount",{AppID:CurrentApp,MenuID:menuid,Hash:h},null);
					}
				}
				
				
			}
		}	
	};
	Application.setCurrentMenu = function(pathname) {
		if (Efast.getDom("main-menu")) {
			$navMenus.each(function(i){
				var navMenuItem = this;
				var url = navMenuItem.getAttribute('href');
				if (url) {
					if (url.indexOf(pathname) > -1) {
						if (!$(navMenuItem).hasClass('active')) {
							navMenuItem.setActiveMenu();
							return false;
						}
					}
				}
				if (navMenuItem._childMenu) { // 查找与当前页面地址匹配的菜单，然后高亮
					var $links = $(navMenuItem._childMenu).find('li');
					$links.each(function(i){
						if (this.getAttribute('href').indexOf(pathname) > -1) {
							if (!$(this).hasClass('active')) {
								this.setActiveMenu();
								return false;
							}
						}
					});
				}
			});
		}
	};
	Application.setPrivParam = function(key,value){
		var win = Efast.rootWin;
		if (!win.Priv) {
			try{//测试发现在firefox下从其他域的页面跳转到ZCMS也存在opener
				if (window.opener && window.opener.Efast) {
					win = window.opener.Efast.rootWin;
				}
			}catch(e){
				win=Efast.rootWin;
			}
		}
		if (win.Priv) {
			if(!win.PrivParams){
				win.PrivParams = {};
			}
			var params = win.PrivParams;
			params[key] = value;
		}
	};
	Application.setAllPriv = function(elem) {
		var $buttons = $("div.mini-menuitem,div.mini-tabs", elem||document);//菜单项
		$buttons.each(function() {
			var btn = mini.get(this.getAttribute("id"));
			if(btn){
				var p = btn.priv;
				if (p) {
					if (!Application.hasPriv(p)) {
						btn.disable();
					}else{
						btn.enable();
					}
				}
			}
		});
	};
	Application.hasPriv = function(privID) {
		var win = Priv.getWin();
		if (win.Priv) {
			var arr = privID.split("||");
			var flag = false;
			if(win.Priv.AdminUserName==win.Priv.UserName){
				flag = true;	
			}else{
				for (var i = 0; i < arr.length; i++) {
					if(!arr[i]){
						continue;
					}
					var item = arr[i];
					if(win.PrivParams){
						for(var k in win.PrivParams){
							item = item.replace("${"+k+"}",win.PrivParams[k]);//替换变量
						}
					}
					if (win.PrivInstance.hasPriv(item)) {
						flag = true;
					}
				}
			}
			return flag;
		}
		return false;
	};
	
	
	Priv = {};
	Priv.getWin = function(){
		var win = Efast.rootWin;
		if (!win.Priv||!win.Priv.Init) {
			try{//测试发现在firefox下从其他域的页面跳转到ZCMS也存在opener
				if (win.opener && win.opener.Efast) {
					win = win.opener.Efast.rootWin;
				}
			}catch(e){
				win=Efast.rootWin;
			}
		}
		return win;
	};
	
	Priv.init = function(obj) {
		if(!obj){
			return;
		}
		var win = Priv.getWin();
		if(win != window){
			win.obj = win.JSON.parse(JSON.stringify(obj));
			win.PrivInstance = new win.Privilege(win.obj);
		}else{
			win.PrivInstance = new Privilege(obj);
		}
		win.Priv.Init = true;
	};

	Priv.charToFlag = function(flag) {
		var i = 0;
		if(flag==36||flag==37){
			i = flag;	
		}else	if (flag < 58) {
			i = flag - 48;
		} else if (flag < 91) {
			i = flag - 27;
		} else if (flag < 123) {
			i = flag - 87;
		}
		return i;
	};
	
	Privilege = function(obj){
		if(typeof(obj)==='string'){
			obj=JSON.parse(obj);
		}
		this.Data = obj;
	};
		
	Privilege.prototype.hasPriv = function(k){
		if(!k){
			return false;
		}
		var index = k.lastIndexOf('.');
		if (index > 0) {
			var id = k.substring(index + 1);
			if (id.isInt()) {
				k = k.substring(0, index);
				var flags = this.Data.ids[id];
				if (flags == null) {
					return false;
				}
				var order = this.Data.types[k];
				if ((order!==0 && !order) || order >= flags.length * 6) {
					return false;
				}
				var flag = flags.charCodeAt(order / 6);
				return (Priv.charToFlag(flag) & 1 << (5 - order % 6)) != 0;
			} else {
				return this.Data.keys[k];
			}
		} else {
			return this.Data.keys[k];
		}
	};
	
	Page.onReady(function() {
		//按钮样式
        Waves.attach('.btn', ['waves-button', 'waves-float']);
        Waves.init();
        /*
         * Text Feild
         */
        
        //Add blue animated border and remove with condition when focus and blur
        if($('.fg-line')[0]) {
            $('body').on('focus', '.form-control', function(){
                $(this).closest('.fg-line').addClass('fg-toggled');
            });
            $('body').on('blur', '.form-control', function(){
                var p = $(this).closest('.form-group');
                var i = p.find('.form-control').val();
                
                if (p.hasClass('fg-float')) {
                    if (i.length == 0) {
                        $(this).closest('.fg-line').removeClass('fg-toggled');
                    }
                }
                else {
                    $(this).closest('.fg-line').removeClass('fg-toggled');
                }
            });
        }
        
        //Add blue border for pre-valued fg-flot text feilds
        if($('.fg-float')[0]) {
            $('.fg-float .form-control').each(function(){
                var i = $(this).val();
                if (!i.length == 0) {
                    $(this).closest('.fg-line').addClass('fg-toggled');
                }
                
            });
        }
        //载入样式
        var skin = Cookie.get("_skin");
        var a;
    	if(skin && (a = document.createElement("link"), a.href = Efast.CONTEXTPATH + "framework/skins/" + skin + ".min.css", a.rel = "stylesheet", document.getElementsByTagName("head")[0].appendChild(a))){
    		Config.skin= skin;
    	}
		var i;
		var nav = Efast.getDom('main-menu'),
		sideNav = Efast.getDom('sidebar');
		if (nav && sideNav) {
			$navMenus = $(nav).find('a');
			Application.initNavMenu(nav, sideNav);// 导航菜单初始化
			var h = window.location.hash || Cookie.get('lastNavStatus');
			h = h && h.replace(/^#*/,'');
			if (!h) {
				if($navMenus && $navMenus.length > 0) {
					h=$navMenus[0].getAttribute('menuid');
					if($navMenus[0]._childMenu){
						var firstSubMenu=$navMenus[0]._childMenu.getElementsByTagName('A')[0];
						if(firstSubMenu){
							h+='/'+firstSubMenu.getAttribute('menuid');
						}
					}
				}
			}
			Application._handleHashChange(h);
		}
		
		if (!Efast.restricted && window.frameElement && window.frameElement.id == "_MainArea") {
			parent.Application.setCurrentMenu(window.location.pathname);
		}
		
		Application.setAllPriv();
		if($('div.ui-page-container').on){
			$('div.ui-page-container').on('pagechange',function(e){
				Application.setAllPriv(this);
			});
		}
	});

	if(window.location.pathname.indexOf('/start')>=0){
		$window.bind( "hashchange", function( e, triggered ) {
			Application._handleHashChange( location.hash.replace(/^#*/,'') );
		});
		$window.on('unload', function() {
			if (window.location.hash) {
				var initdata = location.hash.match(/([\w\.]+)(\/([\w\.]+))?/);
				if (initdata && initdata.length) {
					var navMenuId = initdata[1],
					subNavMenuId = initdata[3];
					Cookie.set('lastNavStatus', navMenuId + '/' + subNavMenuId);
				}
			}
		})
	}
})();